package thread;

class MyBlockingQueue{
    private String[] data = new String[100];
    private volatile int size = 0;
    private volatile int head = 0;
    private volatile int tail = 0;

    public void put(String data) throws InterruptedException {
        synchronized (this) {
            while (size == data.length()){
                this.wait();
            }

            this.data[tail++] = data;
            if (tail == this.data.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (this) {
            while (size == 0){
                this.wait();
            }

            String data = this.data[head++];
            if (head == this.data.length){
                head = 0;
            }
            size--;
            this.notify();
            return data;
        }
    }
}

public class Demo24 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();


        Thread t1 = new Thread(() -> {
            while (true){
                try {
                    String data = queue.take();
                    System.out.println("消费元素：" + data);

                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            int num  = 1;
            while (true){
                try {
                    queue.put(num + "");
                    System.out.println("生产元素：" + num);
                    num++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });

        t1.start();
        t2.start();
    }
}
